package com.xuerhua.yxt.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xuerhua.yxt.common.Const;
import com.xuerhua.yxt.common.MenuConst;
import com.xuerhua.yxt.common.enums.CoachType;
import com.xuerhua.yxt.common.enums.DictDataCode;
import com.xuerhua.yxt.common.enums.LeaveStatus;
import com.xuerhua.yxt.dao.AttachmentListMapper;
import com.xuerhua.yxt.dao.ParentInfoMapper;
import com.xuerhua.yxt.dao.SchoolWechatTemplateMapper;
import com.xuerhua.yxt.dao.StudentCoachMapper;
import com.xuerhua.yxt.dao.StudentLeaveMapper;
import com.xuerhua.yxt.dao.TeacherInfoMapper;
import com.xuerhua.yxt.model.SchoolInfo;
import com.xuerhua.yxt.model.StudentCoach;
import com.xuerhua.yxt.model.StudentLeave;
import com.xuerhua.yxt.model.TeacherInfo;
import com.xuerhua.yxt.page.Page;
import com.xuerhua.yxt.reqVo.AttachRelationReqVO;
import com.xuerhua.yxt.reqVo.ParentReqVO;
import com.xuerhua.yxt.reqVo.StudentLeaveReqVO;
import com.xuerhua.yxt.service.ISchoolInfoService;
import com.xuerhua.yxt.service.IStudentLeaveService;
import com.xuerhua.yxt.utils.BeanUtils;
import com.xuerhua.yxt.view.ParentRelStudentView;
import com.xuerhua.yxt.view.StudentLeaveView;
import com.xuerhua.yxt.view.TeacherInfoView;
import com.xuerhua.yxt.view.TermView;
import com.xuerhua.yxt.wechat.utils.TemplateUtil;

@Service("studentLeaveService")
public class StudentLeaveServiceImpl implements IStudentLeaveService {

	@Autowired
	private StudentLeaveMapper studentLeaveMapper;
	@Autowired
	private AttachmentListMapper attachmentListMapper;
	@Autowired
	private StudentCoachMapper studentCoachMapper;
	@Autowired
	private TeacherInfoMapper teacherInfoMapper;
	@Autowired
	private ParentInfoMapper parentInfoMapper;
	@Autowired
	private ISchoolInfoService schoolInfoService;
	@Autowired
	private SchoolWechatTemplateMapper schoolWechatTemplateMapper;
	
	@Override
	public int insert(StudentLeaveReqVO reqVO) {
		studentLeaveMapper.insertSelective(reqVO);
		if(reqVO.getIsAttach() != null) {
			AttachRelationReqVO attach = new AttachRelationReqVO();
			attach.setRelationId(Long.valueOf(reqVO.getId()));
			attach.setAttachIds(reqVO.getIds());
			attach.setSchoolId(reqVO.getSchoolId());
			attachmentListMapper.updateRelationIdByIds(attach);
		}
		Map<String, Object> map = new HashMap<>();
		map.put("schoolId", reqVO.getSchoolId());
		map.put("grade", reqVO.getGrade());
		map.put("clazz", reqVO.getClazz());
		TeacherInfo teacher = teacherInfoMapper.selectHeadTeacher(map);
		SchoolInfo school = schoolInfoService.queryInitWechatBySchoolId(teacher.getSchoolId());
		String reqUrl = school.getDomainUrl() + Const.TEACHER_ROLE + MenuConst.STUDENT_LEAVE;
		String templateId = schoolWechatTemplateMapper.selectTemplateKey(
				reqVO.getSchoolId(), DictDataCode.STUDENT_LEAVE.getCode());
		TemplateUtil.stuentLeaveApplySend(school,templateId,teacher.getOpenid(), teacher.getName(), 
				reqVO.getStudentName(), reqVO.getStartTime(), reqVO.getEndTime(), 
				reqVO.getLeaveReason(), reqUrl);
		return 1;
	}

	@Override
	public StudentLeave selectByPrimaryKey(Integer id) {
		return studentLeaveMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(StudentLeave record) {
		return studentLeaveMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public List<StudentLeaveView> selectPendingList(Page<StudentLeaveView> page) {
		return studentLeaveMapper.selectPendingList(page);
	}

	@Override
	public List<StudentLeaveView> selectAuditedListByPage(Page<StudentLeaveView> page) {
		return studentLeaveMapper.selectAuditedListByPage(page);
	}

	@Override
	public int updateAudit(StudentLeave record) {
		StudentLeave leave = studentLeaveMapper.selectByPrimaryKey(record.getId());
		if(leave == null) return -1;
		record.setUpdateTime(new Date());
		int count = studentLeaveMapper.updateByPrimaryKeySelective(record);
		leave.setStatus(record.getStatus());
		leave.setUpdateTime(new Date());
		if(count > 0 && record.getStatus().equals(LeaveStatus.AUDIT_SUCCESS.getCode())) {
			List<TeacherInfo> teacherList = teacherInfoMapper.selectMainClassListByStudentId(leave.getStudentId());
			List<TeacherInfoView> teacherListView = BeanUtils.copyAs(teacherList, TeacherInfoView.class);
			List<StudentCoach> coachList = new ArrayList<>();
			for(TeacherInfoView teacher : teacherListView) {
				StudentCoach coach = new StudentCoach();
				coach.setSchoolId(leave.getSchoolId());
				coach.setSchoolName(leave.getSchoolName());
				coach.setTermId(leave.getTermId());
				coach.setStudentId(leave.getStudentId());
				coach.setStudentName(leave.getStudentName());
				coach.setTeacherId(leave.getTermId());
				coach.setLeaveId(leave.getId());
				coach.setCoachType(CoachType.COACH_LEAVE.getCode());
				coach.setTeacherId(teacher.getId());
				coach.setTeacherName(teacher.getName());
				coach.setSubject(teacher.getSubjectText());
				studentCoachMapper.insertSelective(coach);
				coachList.add(coach);
			}
			new Thread(new StudentLeaveNoticeExecutor(leave, teacherListView)).start();
		}
		new Thread(new StudentLeaveParentNoticeExecutor(leave)).start();
		return count;
	}
	
	class StudentLeaveParentNoticeExecutor implements Runnable {
		
		private StudentLeave leave;
		
		public StudentLeaveParentNoticeExecutor(StudentLeave leave) {
			this.leave = leave;
		}

		@Override
		public void run() {
			try {
				SchoolInfo school = schoolInfoService.queryInitWechatBySchoolId(leave.getSchoolId());
				String reqUrl = school.getDomainUrl() + Const.STUDENT_ROLE + MenuConst.STUDENT_LEAVE + "?sid=" + leave.getStudentId();
				String auditResult = "";
				if(leave.getStatus().equals(LeaveStatus.AUDIT_SUCCESS.getCode())) {
					auditResult = "已批准";
				}else {
					auditResult = "已拒绝：" + leave.getRejectReason();
				}
				ParentReqVO parentReqVO = new ParentReqVO();
				parentReqVO.setStudentId(leave.getStudentId());
				List<ParentRelStudentView> parentList = parentInfoMapper.selectStudentListForParent(parentReqVO);
				String templateId = schoolWechatTemplateMapper.selectTemplateKey(
						leave.getSchoolId(), DictDataCode.STUDENT_LEAVE.getCode());
				for(ParentRelStudentView parent : parentList) {
					school = schoolInfoService.refreshInitWechat(school);
					TemplateUtil.studentLeaveAuditSend(school,templateId,parent.getOpenid(), parent.getName(), leave.getTeacherName(), 
							auditResult, reqUrl);
				}
			} catch (Exception e) { 
	            e.printStackTrace(); 
	        }
		}
	}
	
	class StudentLeaveNoticeExecutor implements Runnable {
		
		private StudentLeave leave;
		
		private List<TeacherInfoView> teacherListView;
		
		public StudentLeaveNoticeExecutor(StudentLeave leave, List<TeacherInfoView> teacherListView) {
			this.leave = leave;
			this.teacherListView = teacherListView;
		}

		@Override
		public void run() {
			try {
				SchoolInfo school = schoolInfoService.queryInitWechatBySchoolId(leave.getSchoolId());
				String reqUrl = school.getDomainUrl() + "/ls/course/coach";
				String grade = TermView.getGradeName(leave.getGrade());
				String gradeClass = grade + "（" + leave.getClazz() + "）班";
				String templateId = schoolWechatTemplateMapper.selectTemplateKey(
						leave.getSchoolId(), DictDataCode.STUDENT_COACH.getCode());
				for(TeacherInfoView teacher : teacherListView) {
					school = schoolInfoService.refreshInitWechat(school);
					TemplateUtil.studentCoachSend(school,templateId,teacher.getOpenid(), teacher.getName(), leave.getStudentName(), 
							gradeClass, leave.getStartTime(), leave.getEndTime(), leave.getLeaveReason(), reqUrl);
				}
			} catch (Exception e) { 
	            e.printStackTrace(); 
	        }
		}
	}

}
